<template>
  <el-card class="box-card">
    <template #header>
      请登录
    </template>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="70px" status-icon>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item>
        <el-button @click="resetForm(ruleFormRef)">
          重置
        </el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button >
          <router-link to="/UserRegistration">去注册</router-link>
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      Footer content
    </template>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Login } from "../../api/user/"

interface RuleForm {
  username: string
  password: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  username: '',
  password: '',
})

const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度3-10', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 10, message: '长度3-10', trigger: 'blur' },
  ],

})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(ruleForm);
      console.log(toRaw(ruleForm));
      const result = Login(toRaw(ruleForm));
      result.then((res) => {
        if (res.code === 200) {
          console.log(res.data);
          localStorage.setItem("Authorization", res.data)
          console.log(localStorage.getItem("Authorization"));
        } else {
          return ElMessage({
            showClose: true,
            message: '用户名或密码错误',
            type: 'error',
          })
        }
      })

    } else {
      return ElMessage({
        showClose: true,
        message: '请检查参数',
        type: 'error',
      })
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>



<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 90vw;
  margin: 40px auto;
}
</style>